﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using CivilRegistry.ControlledModel.Extensions;

namespace CivilRegistry.Networking
{
    /// <summary>
    /// The object to send SMS.
    /// </summary>
    public class SMSEngine
    {
        private long phoneNumber;

        /// <summary>
        /// Gets or sets the Phone number.
        /// </summary>
        public long PhoneNumber
        {
            get { return phoneNumber; }
            set { phoneNumber = value; }
        }
        private string message;

        /// <summary>
        /// Gets or sets the message.
        /// </summary>
        public string Message
        {
            get { return message; }
            set { message = value; }
        }

        /// <summary>
        /// To send the SMS.
        /// </summary>
        /// <returns>Returns True if succeeded, else false.</returns>
        public bool Send()
        {
            return this.Send(this.phoneNumber, this.message);
        }

        /// <summary>
        /// To send the SMS.
        /// </summary>
        /// <param name="phoneNumber">The phone number.</param>
        /// <param name="message">The message.</param>
        /// <returns>Returns True if succeeded, else false.</returns>
        public bool Send(long phoneNumber, string message)
        {
            phoneNumber.Required("PhoneNumber");
            message.Required("Message");

            if (phoneNumber.ToString().Length != 10)
            {
                throw new ApplicationException("Invalid Phone Number.");
            }

            if (message.ToCharArray().Count() > 140)
            {
                throw new ApplicationException("The characters exceeded the limit. Maximum allowed characters is 140");
            }

            string url = string.Format("http://ubaid.tk/sms/sms.aspx?uid={0}&pwd={1}&msg={2}&phone={3}&provider=way2sms",
                            ConfigurationManager.AppSettings["Way2SMSUserId"], ConfigurationManager.AppSettings["Way2SMSPassword"], message, phoneNumber);
            try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);

                using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    httpResponse.GetResponseStream(); //Ignore the response
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                return false;
            }
            return true;
        }
    }
}